package com.ruoyi.mongo.service;

import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.mongo.word.entity.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.List;

import static com.ruoyi.mongo.service.MongoService.getDataCommon;

@Slf4j
@Service
public class MongoPrimaryService {

    // 注入第二个数据库的 MongoTemplate
    private final MongoTemplate secondaryMongoTemplate;

    public final MongoListService mongoListService;

    public MongoPrimaryService(@Qualifier("secondaryMongoTemplate")
                               MongoTemplate secondaryMongoTemplate,
                               MongoListService mongoListService
    ) {
        this.secondaryMongoTemplate = secondaryMongoTemplate;
        this.mongoListService = mongoListService;
    }

    //初中-数据-查询
    public List<WordPrimaryEntity> getPrimaryData(String unit , String book, Long userId) {
        Query query = getDataCommon(unit, book);
        if (unit == null || unit.isEmpty()) {
            query.limit(MongoConstants.MONGO_MAX_GROUP_SIZE);
        }
        String collection = MongoConstants.COLLECT_WORD_PRIMARY;
        List<WordPrimaryEntity> list = secondaryMongoTemplate.find(query, WordPrimaryEntity.class, collection);
        log.info("查询:{}-初中-条件:{}-条数:{}-结果:{}-用户:{}",collection, query.getQueryObject().toJson(), list.size(), !list.isEmpty(),userId);
        return list;
    }

    public List<WordPrimaryEntity> getPrimaryData(String unit , String book,int times,Long userId) {
        String collection = MongoConstants.COLLECT_WORD_PRIMARY;
        List<WordPrimaryEntity> list = getPrimaryData(unit, book,userId);
        if (times == 1){
            return list;
        }
        else {
            long floored = Math.floorDiv(list.size(), times);
            Criteria criteria = MongoService.getDataCriteria(unit, book);
            Aggregation aggregation = Aggregation.newAggregation(Aggregation.match(criteria), Aggregation.sample(floored));
            AggregationResults<WordPrimaryEntity> results = secondaryMongoTemplate.aggregate(aggregation, collection, WordPrimaryEntity.class);
            List<WordPrimaryEntity> entityList = results.getMappedResults();
            log.info("查询:{}-初中-条件:times = {}-条数:{}-结果:{}",collection, times, entityList.size(), !entityList.isEmpty());
            return entityList;
        }
    }

    //初中-数据-查询
    public List<WordStudyEntity> getPrimaryStudyData(String practiceId , String collectionName) {
        Query query = new Query();
        query.addCriteria(Criteria.where("practiceId").is(practiceId));
        List<WordStudyEntity> list = secondaryMongoTemplate.find(query, WordStudyEntity.class, collectionName);
        log.info("查询:{}-初中-条件:{}-条数:{}-结果:{}",collectionName, query.getQueryObject().toJson(), list.size(), !list.isEmpty());
        return list;
    }

    //初中-数据-查询
    public List<WordStudyEntity> getPrimaryStudyData(String unit , String book,String collectionName) {
        Query query = getDataCommon(unit, book);
        List<WordStudyEntity> list = secondaryMongoTemplate.find(query, WordStudyEntity.class, collectionName);
        log.info("查询:{}-初中-条件:{}-条数:{}-结果:{}",collectionName, query.getQueryObject().toJson(), list.size(), !list.isEmpty());
        return list;
    }

    //初中-数据保存-学习
    public void savePrimaryStudyData(WordStudyEntity entity , String collectionName) {
        entity.set_id(null);
        WordStudyEntity insert = secondaryMongoTemplate.insert(entity, collectionName);
        log.info("保存-集合:{},主键:{},时间:{}", collectionName, insert.get_id(), DateUtils.getLocalTime());
    }

    //初中-数据保存-测试-data
    public void savePrimaryTestData(WordTestEntity entity , String collectionName) {
        entity.set_id(null);
        WordTestEntity insert = secondaryMongoTemplate.insert(entity, collectionName);
        log.info("保存-集合:{},主键:{},时间:{}", collectionName, insert.get_id(), DateUtils.getLocalTime());
    }

    //初中-数据保存-测试-data
    public void savePrimaryTestData(WordCheckNewRecord entity , String collectionName) {
        entity.set_id(null);
        WordCheckNewRecord insert = secondaryMongoTemplate.insert(entity, collectionName);
        log.info("保存-集合:{},主键:{},时间:{}", collectionName, insert.get_id(), DateUtils.getLocalTime());
    }

    //初中-数据保存-测试-list
    public void savePrimaryTestData(List<WordTestEntity> list , String collectionName) {
        list.forEach(entity -> savePrimaryTestData(entity , collectionName));
    }

    //初中-数据-查询
    public List<WordTestEntity> getPrimaryTestData(String unit , String book,String collectionName) {
        Query query = getDataCommon(unit, book);
        List<WordTestEntity> list = secondaryMongoTemplate.find(query, WordTestEntity.class, collectionName);
        log.info("查询:{}-初中-条件:{}-条数:{}-结果:{}",collectionName, query.getQueryObject().toJson(), list.size(), !list.isEmpty());
        return list;
    }

    //初中-数据-查询
    public List<WordCheckNewRecord> getPrimaryTestDetail(String practiceId , String collectionName) {
        Query query = new Query();
        query.addCriteria(Criteria.where("practiceId").is(practiceId));
        List<WordCheckNewRecord> list = secondaryMongoTemplate.find(query, WordCheckNewRecord.class, collectionName);
        log.info("查询:{}-初中-条件:{}-条数:{}-结果:{}",collectionName, query.getQueryObject().toJson(), list.size(), !list.isEmpty());
        return list;
    }

    public List<?> getPrimaryTestDataNew(String practiceId , Long userId) {
        String collection = MongoConstants.COLLECT_WORD_PRIMARY_TEST + "_" + userId;
        List<?> list = getPrimaryTestDetail(practiceId, collection);
        if (list.isEmpty()){
            String collectionName = MongoConstants.COLLECT_WORD_CHECK_NEW_RECORD + "_" + userId;
            list =  mongoListService.getAllListData(collectionName,practiceId);
        }
        return list;
    }

    public List<?> getPrimaryTestDetail(String practiceId , Long userId) {
        String collection = MongoConstants.COLLECT_WORD_PRIMARY_TEST + "_" + userId;
        return getPrimaryTestDetail(practiceId,collection);
    }

    //初中-数据保存-汉译英
    public void savePrimaryWriteData(WordChinToEngEntity entity , String collectionName) {
        entity.set_id(null);
        WordChinToEngEntity insert = secondaryMongoTemplate.insert(entity, collectionName);
        log.info("保存-集合:{},主键:{},时间:{}", collectionName, insert.get_id(), DateUtils.getLocalTime());
    }

    //初中-数据查询-汉译英
    public List<WordChinToEngEntity> getPrimaryWriteData(String practice, String collectionName){
        Query query = new Query();
        query.addCriteria(Criteria.where(MongoConstants.MONGO_PRACTICE).is(practice));
        return getPrimaryWriteData(query,collectionName);
    }

    //初中-数据查询-汉译英
    public List<WordChinToEngEntity> getPrimaryWriteData(Query query ,String collectionName) {
        List<WordChinToEngEntity> list = secondaryMongoTemplate.find(query, WordChinToEngEntity.class, collectionName);
        log.info("集合:{}-条件:{}-数据条数为:{}", collectionName, query.getQueryObject().toJson(), list.size());
        return list;
    }
}
